package lsieun.visitor;

import lsieun.cst.Constant;
import lsieun.utils.NameUtils;
import lsieun.utils.PrintUtils;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

public class StackTraceVisitor extends ClassVisitor {
    public StackTraceVisitor(ClassVisitor classVisitor) {
        super(Constant.API_VERSION, classVisitor);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor mv = super.visitMethod(access, name, descriptor, signature, exceptions);
        if (mv != null && !"<init>".equals(name) && !"<clinit>".equals(name)) {
            mv = new StackTraceAdapter(mv);
        }
        return mv;
    }

    private class StackTraceAdapter extends MethodVisitor {
        private final String internalName = NameUtils.toInternalName(PrintUtils.class.getName());

        public StackTraceAdapter(MethodVisitor methodVisitor) {
            super(Constant.API_VERSION, methodVisitor);
        }

        @Override
        public void visitCode() {
            super.visitMethodInsn(Opcodes.INVOKESTATIC, internalName, "printStackTrace", "()V", false);
            super.visitCode();
        }
    }
}
